<template>
	<view class="container" @click.self="type == 1 ? closePopup : ''">
		<view class="area">
			<image class="close" v-if="type == 1" @click="closePopup" src="../../static/langwen/close.png" mode=""></image>
			<view class="goods">
				<image class="img" :src="sku.pic || goods.pic" mode=""></image>
				<view class="flexbox">
					<view class="price">
						¥{{ sku.price == undefined ? goods.price : sku.price }}
					</view>
					<view class="stock">
						库存&nbsp;{{ sku.stock == undefined ?  goods.stock : sku.stock }}
					</view>
					<view class="selected">
						已选：
                        <text class="selected-text" v-for="(sItem, sIndex) in specSelected" :key="sIndex">{{ sItem.name }}</text>
						<text v-show="!specSelected.length">请选择</text>
					</view>
				</view>
			</view>
			<view class="option">
                <view v-for="(item, index) in specList" :key="index">
                    <view class="title">{{item.name}}</view>
                    <view class="items">
                    	<view   class="item" 
                                v-for="(childItem, childIndex) in specChildList"
                                v-if="childItem.pid === item.id"
                                :key="childIndex"
                                :class="{ active: childItem.selected }"
                                @click="selectSpec(childIndex, childItem.pid)">
                    		{{ childItem.name }}
                    	</view>
                    </view>
                </view>
				
			</view>
			<view class="count">
				<view class="title">
					购买数量
				</view>
				<view class="right">
					<image class="btn" src="../../static/langwen/reduce_2.png" mode="" @click="countNum > 1 ? countNum-- : countNum"></image>
					<view class="number">
						{{ countNum }}
					</view>
					<image class="btn" src="../../static/langwen/add_2.png" mode="" @click="countNum++"></image>
				</view>
			</view>
			<view class="btns">
				<view class="btn-blue" v-if="type == 1" @click="joinCart">
					加入购物车
				</view>
				<view class="btn-yellow" v-if="type == 1" @click="joinCart" data-option="buy">
					立即购买
				</view>
                <view class="btn-blue" v-if="type == 2" @click="changeCart">
					确定
				</view>
                <view class="btn-yellow" v-if="type == 2" @click="$emit('close-popup');">
					取消
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import Api from '@/common/api';
export default {
	name: 'popup',
    props: ['id','selected','type', 'goodsNum', 'shareTeacher'],
    data() {
        return {
            sku: {},
            skuList: [],
            specList: [],
            specChildList: [],
            specSelected: [],
            goods: {},
            countNum: this.goodsNum || 1,
			isSuccess: false
        }
    },
    created() {
        this.getData();
    },
	methods: {
        //选择规格
        selectSpec(index, pid) {
        	let list = this.specChildList;
        	list.forEach(item => {
        		if (item.pid === pid) {
        			this.$set(item, 'selected', false);
        		}
        	});
        
        	this.$set(list[index], 'selected', true);
        	//存储已选择
        	/**
        	 * 修复选择规格存储错误
        	 * 将这几行代码替换即可
        	 * 选择的规格存放在specSelected中
        	 */
        	var specs = '';
        	this.specSelected = [];
        	list.forEach(item => {
        		if (item.selected === true) {
        			this.specSelected.push(item);
        			specs = item.name + ',' + specs;
        		}
        	});
        	let valuesA = specs.substr(0, specs.length - 1).split(',');
        
        	this.skuList.forEach(item => {
        		if (valuesA.length == 1 && item.sp1 == valuesA[0]) {
        			this.sku = item;
        		}
        		if (valuesA.length == 2 && item.sp2 == valuesA[0] && item.sp1 == valuesA[1]) {
        			this.sku = item;
        		}
        		if (valuesA.length == 3 && item.sp3 == valuesA[0] && item.sp2 == valuesA[1] && item.sp1 == valuesA[2]) {
        			this.sku = item;
        		}
        		if (!this.sku.pic) {
        			this.sku.pic = this.goods.pic;
        		}
        		if (!this.sku.stock) {
        			this.sku.stock = 0;
        		}
        		if (!this.sku.price) {
        			this.sku.price = this.goods.price;
        		}
        	});
        },
		closePopup() {
            // 关闭弹窗
            let result = '';
            if(this.specSelected && this.specSelected.length > 0) {
                for(let i = 0; i < this.specSelected.length; i ++) {
                    result += this.specSelected[i].name;
                }
            }
			if(this.isSuccess) {
				this.$emit('close-popup', result, this.countNum);
			} else {
				this.$emit('close-popup', result);
			}
        },
        changeCart() {
            if(this.sku.id && this.specSelected.length == this.specList.length) {
                this.$emit('close-popup', this.sku, this.countNum)
            }else {
                uni.showToast({title: '请选择规格'});
            }
        },
        async getData() {
            var params = {
                'id': this.$props.id
            };
            var data = await Api.apiCall('get', Api.goods.goodsDetail, params);
            this.goods = data.goods.goods;
            this.skuList = data.goods.skuStockList;
            this.specList = data.goods.productAttributeValueList;
            if (this.specList) {
            	this.specList.forEach(item => {
            		let valuesA = item.value.split(',');
            		if (valuesA) {
            			for (let cItem of valuesA) {
            				let att = {};
            				att.pid = item.id;
            				att.name = cItem;
            				this.specChildList.push(att);
            			}
            		}
            	});
            }
        },
        canHandle() {
            let  msg = null;
            if(!this.sku.id || this.specSelected.length != this.specList.length) {
                msg = '请选择规格';
            } else if(this.countNum > this.sku.stock) {
                msg = '库存不足';
            }
            this.$api.msg(msg);
            return !msg;
        },
		async payHandle(cartId) {
            // 立即支付
            var params = {
                'type': '1',
                'source': '2',
                'orderType': '1',
                'goodsId': this.id,
                'cartId': cartId,
                'addressId': '',
                'payType': '',
                'isBuyTeacherRecommendGoods': this.$props.shareTeacher ? 1 : 2
            };
            var data = await Api.apiCall('get', Api.goods.priviewOrder, params);
            // 路径
            var url = '/pages/langwen/confirm';
            // 参数
            params.orderInfo = data;
            uni.navigateTo({
                url: `${url}?param=${encodeURIComponent(JSON.stringify(params))}`
            });
            this.closePopup();
        },
        async joinCart(e) {
            // 加入购物车
            if(!this.canHandle()) return;
            var params = {
                'goodsId': this.id,
                'skuId': this.sku.id,
                'total': this.countNum,
                'buyRoad': e.target.dataset.option == 'buy' ? '2' : '1'
            };
            var data = await Api.apiCall('get', Api.goods.joinCart, params);
            if(!data) {
                // uni.showToast({
                // 	title: '加入购物车失败',
                // 	icon: 'none'
                // });
				this.isSuccess = false;
            }else if(e.target.dataset.option == 'buy') {
                this.payHandle(data.id);
            }else {
                uni.showToast({
                	title: '加入购物车成功',
                	icon: 'none'
                });
				this.isSuccess = true;
                this.closePopup();
            }
        }
	}
}
</script>

<style lang="less">
.container {
	z-index: 999;
	position: fixed;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	background:rgba(0,0,0,0.49);
	.area {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: auto;
		background: #fff;
		padding: 0 15px;
		border-radius: 10px 10px 0px 0px;
		.close {
			position: absolute;
			right: 15px;
			top: 15px;
			height: 22px;
			width: 22px;
		}
		.goods {
			display: flex;
			padding: 15px 0;
			border-bottom: 1px solid rgb(239,239,239);
			.img {
				width: 75px;
				height: 100px;
				min-width: 75px;
				margin-right: 20px;
			}
			.flexbox {
				flex-grow: 1;
				padding-top: 28px;
				.price {
					font-size:20px;
					font-weight:500;
					color:rgba(255,92,1,1);
				}
				.stock {
					font-size:12px;
					font-weight:400;
					color:rgba(204,204,204,1);
					letter-spacing:1px;
					margin-top: 5px;
				}
				.selected {
					font-size:12px;
					font-weight:400;
					color:rgba(51,51,51,1);
					letter-spacing:1px;
					margin-top: 5px;
				}
			}
		}
		.option {
			padding: 15px 0;
			height: 246px;
			overflow-x: hidden;
			overflow-y: auto;
			border-bottom: 1px solid rgb(239,239,239);
			.title {
				font-size:14px;
				font-weight:400;
				color:rgba(48,48,51,1);
				letter-spacing:1px;
			}
			.items {
				display: flex;
				flex-wrap: wrap;
				.item {
					display: flex;
					align-items: center;
					padding: 0 15px;
					height: 30px;
					background:rgba(247,247,247,1);
					border-radius:15px;
					font-size:13px;
					font-weight:400;
					color:rgba(48,48,51,1);
					letter-spacing:1px;
					margin-top: 20rpx;
					margin-bottom: 20rpx;
					margin-right: 20rpx;
                }
                .active {
                    background:rgba(90,194,255,1);
                    font-size:13px;
                    font-weight:400;
                    color:rgba(255,255,255,1);
                }
			}
		}
		.count {
			display: flex;
			height: 54px;
			align-items: center;
			justify-content: space-between;
			.title {
				font-size:14px;
				font-weight:400;
				color:rgba(48,48,51,1);
				letter-spacing:1px;
			}
			.right {
				display: flex;
				align-items: center;
				.btn {
					width: 24px;
					min-width: 24px;
					height: 24px;
				}
				.number {
					font-size:16px;
					font-weight:600;
					color:rgba(51,51,51,1);
					letter-spacing:1px;
					margin: 0 15px;
				}
			}
		}
		.btns {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 70px;
			margin: 0 -15px;
			box-sizing: content-box;
			border-top: 10px solid rgba(245,245,245,1);
			.btn-blue {
				display: flex;
				justify-content: center;
				align-items: center;
				width:130px;
				height:40px;
				background:rgba(90,194,255,1);
				border-radius:20px;
				font-size:15px;
				font-weight:500;
				color:rgba(255,255,255,1);
			}
			.btn-yellow {
				display: flex;
				justify-content: center;
				align-items: center;
				width:130px;
				height:40px;
				background:rgba(253,155,67,1);
				border-radius:20px;
				font-size:15px;
				font-weight:500;
				color:rgba(255,255,255,1);
				margin-left: 25px;
			}
		}
	}
}
</style>
